package com.ungao.servlet;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

import java.io.IOException;

public abstract class AbstractHttpServlet implements HttpHandler {

    @Override
    public void handle(HttpExchange httpExchange) throws IOException {
        HttpServletRequest request = new HttpServletRequest(httpExchange);
        HttpServletResponse response = new HttpServletResponse(httpExchange);
        try {
            this.dispatcher(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
        httpExchange.close();
    }

    public AbstractHttpServlet config(String contextConfigLocation) {
        this.init(contextConfigLocation);
        return this;
    }

    protected abstract void init(String contextConfigLocation);

    protected abstract void dispatcher(HttpServletRequest request, HttpServletResponse response) throws Exception;
}
